package net.ruixin.session;

import lombok.AllArgsConstructor;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Redis session实现
 * @author mxding
 * @date 2021-04-23 15:52
 */
@Service
@AllArgsConstructor
public class RedisSessionDao extends AbstractSessionDAO {

    private RedisTemplate<Serializable, Session> redisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.generateSessionId(session);
        super.assignSessionId(session, sessionId);
        redisTemplate.opsForValue().set(sessionId, session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return redisTemplate.opsForValue().get(sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        redisTemplate.opsForValue().set(session.getId(), session);
    }

    @Override
    public void delete(Session session) {
        redisTemplate.opsForValue().getOperations().delete(session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Session> sessions = new HashSet<>();
        Set<Serializable> keys = redisTemplate.keys("*");
        if (keys != null && keys.size() > 0) {
            for (Serializable key : keys) {
                Session s = redisTemplate.opsForValue().get(key);
                sessions.add(s);
            }
        }
        return sessions;
    }
}
